
// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import NECommonUIKit
import NECoreIM2Kit
import NIMSDK
import UIKit

@objcMembers
open class TeamSettingViewController: NEBaseTeamSettingViewController {
    
    var canAdd: Bool = false
    var canDelete: Bool = false
    
    override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        className = "TeamSettingViewController"
        cellClassDic = [
            SettingCellType.SettingArrowCell.rawValue: TeamArrowSettingCell.self,
            SettingCellType.SettingSwitchCell.rawValue: TeamSettingSwitchCell.self,
            SettingCellType.SettingSelectCell.rawValue: TeamSettingSelectCell.self,
            SettingCellType.SettingSubtitleCell.rawValue: TeamSettingDetailCell.self,
        ]
    }
    
    /// 背景视图
    public lazy var backView: UIView = {
        let backView = UIView()
        backView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 172)
        return backView
    }()
    
    /// 圆角视图
    public lazy var cornerView: UIView = {
        let cornerView = UIView()
        cornerView.backgroundColor = .white
        cornerView.clipsToBounds = true
        cornerView.translatesAutoresizingMaskIntoConstraints = false
        cornerView.layer.cornerRadius = 6.0
        return cornerView
    }()
    
    /// 群信息跳转下一级页面指示箭头
    lazy var arrowImageView: UIImageView = {
        let arrowImageView = UIImageView()
        arrowImageView.translatesAutoresizingMaskIntoConstraints = false
        arrowImageView.image = coreLoader.loadImage("right_arrow_icon")
        return arrowImageView
    }()
    
    /// 分隔线
    lazy var dividerLineView: UIView = {
        let dividerLineView = UIView()
        dividerLineView.translatesAutoresizingMaskIntoConstraints = false
        //    dividerLineView.backgroundColor = NEConstant.hexRGB(0xF5F8FC)
        return dividerLineView
    }()
    
    /// 成员列表跳转下一级页面指示箭头
    public var memberArrowImageView: UIImageView = {
        let memberArrowImageView = UIImageView()
        memberArrowImageView.translatesAutoresizingMaskIntoConstraints = false
        memberArrowImageView.image = coreLoader.loadImage("right_arrow_icon")
        return memberArrowImageView
    }()
    
    /// 群成员列表按钮
    public var memberListButton: UIButton = {
        let memberListButton = UIButton()
        memberListButton.translatesAutoresizingMaskIntoConstraints = false
        return memberListButton
    }()
    
    /// 群信息页面跳转按钮
    public var infoButton: UIButton = {
        let infoButton = UIButton()
        infoButton.translatesAutoresizingMaskIntoConstraints = false
        return infoButton
    }()
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override open func setupUI() {
        super.setupUI()
        navigationView.backgroundColor = .normalTeamBackColor
        navigationController?.navigationBar.backgroundColor = .normalTeamBackColor
        
        teamHeaderView.layer.cornerRadius = 20.0
        addButton.setImage(coreLoader.loadImage("member_add"), for: .normal)
        cellAddButton.setImage(coreLoader.loadImage("member_add"), for: .normal)
        cellDeleteButton.setImage(coreLoader.loadImage("member_remove"), for: .normal)
    }
    
    /// 获取顶部视图
    override open func getHeaderView() -> UIView {
        backView.addSubview(cornerView)
        NSLayoutConstraint.activate([
            cornerView.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: kScreenInterval),
            cornerView.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -kScreenInterval),
            cornerView.topAnchor.constraint(equalTo: backView.topAnchor, constant: 12),
            cornerView.bottomAnchor.constraint(equalTo: backView.bottomAnchor),
        ])
        
        cornerView.addSubview(teamHeaderView)
        NSLayoutConstraint.activate([
            teamHeaderView.leftAnchor.constraint(equalTo: cornerView.leftAnchor, constant: 12),
            teamHeaderView.topAnchor.constraint(equalTo: cornerView.topAnchor, constant: 12),
            teamHeaderView.widthAnchor.constraint(equalToConstant: 40),
            teamHeaderView.heightAnchor.constraint(equalToConstant: 40),
        ])
        
        setTeamHeaderInfo()
        
        cornerView.addSubview(teamNameLabel)
        NSLayoutConstraint.activate([
            teamNameLabel.leftAnchor.constraint(equalTo: teamHeaderView.rightAnchor, constant: 12),
            teamNameLabel.centerYAnchor.constraint(equalTo: teamHeaderView.centerYAnchor),
            teamNameLabel.rightAnchor.constraint(equalTo: cornerView.rightAnchor, constant: -44),
        ])
        
        cornerView.addSubview(arrowImageView)
        NSLayoutConstraint.activate([
            arrowImageView.centerYAnchor.constraint(equalTo: teamHeaderView.centerYAnchor),
            arrowImageView.rightAnchor.constraint(equalTo: cornerView.rightAnchor, constant: -12),
        ])
        
        cornerView.addSubview(dividerLineView)
        NSLayoutConstraint.activate([
            dividerLineView.heightAnchor.constraint(equalToConstant: 1.0),
            dividerLineView.rightAnchor.constraint(equalTo: cornerView.rightAnchor),
            dividerLineView.leftAnchor.constraint(equalTo: cornerView.leftAnchor, constant: 12.0),
            dividerLineView.topAnchor.constraint(equalTo: teamHeaderView.bottomAnchor, constant: 12.0),
        ])
        
        cornerView.addSubview(memberLabel)
        NSLayoutConstraint.activate([
            memberLabel.leftAnchor.constraint(equalTo: dividerLineView.leftAnchor),
            memberLabel.topAnchor.constraint(equalTo: dividerLineView.bottomAnchor, constant: 12),
        ])
        
        if teamSettingType == .Senior {
            memberLabel.text = localizable("group_memmber")
        } else {
            memberLabel.text = localizable("discuss_mebmer")
        }
        
        cornerView.addSubview(memberArrowImageView)
        NSLayoutConstraint.activate([
            memberArrowImageView.rightAnchor.constraint(equalTo: arrowImageView.rightAnchor),
            memberArrowImageView.centerYAnchor.constraint(equalTo: memberLabel.centerYAnchor),
        ])
        
        cornerView.addSubview(memberListButton)
        memberListButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            memberListButton.leftAnchor.constraint(equalTo: memberLabel.leftAnchor),
            memberListButton.rightAnchor.constraint(equalTo: memberArrowImageView.rightAnchor),
            memberListButton.centerYAnchor.constraint(equalTo: memberLabel.centerYAnchor),
            memberListButton.heightAnchor.constraint(equalToConstant: 40),
        ])
        memberListButton.addTarget(self, action: #selector(toMemberList), for: .touchUpInside)
        
        cornerView.addSubview(memberCountLabel)
        NSLayoutConstraint.activate([
            memberCountLabel.rightAnchor.constraint(equalTo: memberArrowImageView.leftAnchor, constant: 0),
            memberCountLabel.centerYAnchor.constraint(equalTo: memberArrowImageView.centerYAnchor),
        ])
        memberCountLabel.text = "\(viewModel.teamInfoModel?.team?.memberCount ?? 0)"
        
        cornerView.addSubview(addButton)
        addButtonWidth = addButton.widthAnchor.constraint(equalToConstant: 40)
        addButtonWidth?.isActive = true
        addButtonLeftMargin = addButton.leftAnchor.constraint(equalTo: cornerView.leftAnchor, constant: 12.0)
        NSLayoutConstraint.activate([
            addButtonLeftMargin!,
            addButton.topAnchor.constraint(equalTo: memberLabel.bottomAnchor, constant: 12),
        ])
        addButton.addTarget(self, action: #selector(addUser), for: .touchUpInside)
        
        if viewModel.isNormalTeam() == false, viewModel.isOwner() == false,
           let inviteMode = viewModel.teamInfoModel?.team?.inviteMode, let member = viewModel.memberInTeam, inviteMode == .TEAM_INVITE_MODE_MANAGER, member.memberRole != .TEAM_MEMBER_ROLE_MANAGER {
            addButtonWidth?.constant = 0
            addButton.isHidden = true
        }
        
        setupUserInfoCollection(cornerView)
        
        cornerView.addSubview(infoButton)
        NSLayoutConstraint.activate([
            infoButton.leftAnchor.constraint(equalTo: teamHeaderView.leftAnchor),
            infoButton.topAnchor.constraint(equalTo: teamHeaderView.topAnchor),
            infoButton.bottomAnchor.constraint(equalTo: teamHeaderView.bottomAnchor),
            infoButton.rightAnchor.constraint(equalTo: arrowImageView.rightAnchor),
        ])
        infoButton.addTarget(self, action: #selector(toInfoView), for: .touchUpInside)
        
        return backView
    }
    
    override open func checkoutAddShowOrHide() {
        addButton.isHidden = true
        addButtonWidth?.constant = 0
        addButtonLeftMargin?.constant = 0
        
        canAdd = true
        canDelete = false
        
        if let member = viewModel.userInTeam, TeamHelper.canDeleteMemeber(member) {
            // 客户经理、客服可移除成员
            canDelete = true
        }
        
        checkMemberCountLimit()
    }
    
    func checkMemberCountLimit() {
        if viewModel.teamInfoModel?.team?.memberLimit == viewModel.teamInfoModel?.team?.memberCount {
            canAdd = false
        }
        
        //        var count = 5
        //
        //        if canDelete {
        //            count -= 1
        //        }
        //
        //        if canAdd {
        //            count -= 1
        //        }
        //
        //        if (viewModel.teamInfoModel?.team?.memberCount ?? 0) > count {
        //            backView.height = 224
        //        } else {
        //            backView.height = 172
        //        }
        //
        //        contentTableView.tableHeaderView = getHeaderView()
    }
    
    override open func getFooterView() -> UIView? {
        guard let title = getBottomText() else {
            return nil
        }
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 46.0))
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        footerView.addSubview(button)
        button.backgroundColor = .white
        button.clipsToBounds = true
        button.setTitleColor(.normalTeamRedColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.setTitle(title, for: .normal)
        button.addTarget(self, action: #selector(removeTeamForMyself), for: .touchUpInside)
        button.layer.cornerRadius = 6.0
        NSLayoutConstraint.activate([
            button.leftAnchor.constraint(equalTo: footerView.leftAnchor, constant: kScreenInterval),
            button.rightAnchor.constraint(equalTo: footerView.rightAnchor, constant: -kScreenInterval),
            button.topAnchor.constraint(equalTo: footerView.topAnchor, constant: 0),
            button.heightAnchor.constraint(equalToConstant: 46),
        ])
        return footerView
    }
    
    override open func setupUserInfoCollection(_ cornerView: UIView) {
        cornerView.addSubview(userinfoCollectionView)
        NSLayoutConstraint.activate([
            userinfoCollectionView.leftAnchor.constraint(equalTo: cornerView.leftAnchor, constant: 12),
            userinfoCollectionView.topAnchor.constraint(equalTo: memberLabel.bottomAnchor, constant: 12),
            userinfoCollectionView.rightAnchor.constraint(equalTo: cornerView.rightAnchor,constant: -12),
            userinfoCollectionView.heightAnchor.constraint(equalToConstant: 40)
        ])
        
        userinfoCollectionView.register(
            TeamUserCell.self,
            forCellWithReuseIdentifier: "\(TeamUserCell.self)"
        )
        userinfoCollectionView.register(
            UICollectionViewCell.self,
            forCellWithReuseIdentifier: "add_cell"
        )
        userinfoCollectionView.register(
            UICollectionViewCell.self,
            forCellWithReuseIdentifier: "delete_cell"
        )
    }
    
    // MARK: objc 方法
    
    override open func toInfoView() {
        let info = TeamInfoViewController(team: viewModel.teamInfoModel?.team)
        navigationController?.pushViewController(info, animated: true)
    }
    
    override open func didClickChangeNick() {
        let nick = TeamNameViewController()
        nick.type = .NickName
        nick.team = viewModel.teamInfoModel?.team
        nick.teamMember = viewModel.memberInTeam
        navigationController?.pushViewController(nick, animated: true)
    }
    
    override open func didClickTeamAnnouncement() {
        let announcement = TeamAnnouncementViewController()
        announcement.team = viewModel.teamInfoModel?.team
        announcement.title = localizable("team_announcement")
        navigationController?.pushViewController(announcement, animated: true)
    }
    
    override open func didClickTeamAlias() {
        guard let tid = teamId else {
            return
        }
        let nick = TeamNameViewController()
        nick.type = .TeamAlias
        nick.team = viewModel.teamInfoModel?.team
        nick.teamMember = viewModel.memberInTeam
        navigationController?.pushViewController(nick, animated: true)
    }
    
    override open func didClickHistoryMessage() {
        guard let tid = teamId else {
            return
        }
        Router.shared.use(
            SearchMessageRouter,
            parameters: ["nav": navigationController as Any, "teamId": tid, "teamInfo": viewModel.teamInfoModel as Any],
            closure: nil
        )
    }
    
    override open func didClickTeamManage() {
        let manageTeam = TeamManagerController()
        manageTeam.viewModel.teamInfoModel = viewModel.teamInfoModel
        navigationController?.pushViewController(manageTeam, animated: true)
    }
    
    override open func collectionView(_ collectionView: UICollectionView,
                                      numberOfItemsInSection section: Int) -> Int {
        let count = viewModel.teamInfoModel?.users.count ?? 0
        if canAdd && canDelete {
            return count + 2
        } else if !canAdd && canDelete {
            return count + 1
        } else if canAdd && !canDelete {
            return count + 1
        } else {
            return count
        }
    }
    
    override open func collectionView(_ collectionView: UICollectionView,
                                      cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if canAdd && canDelete {
            if indexPath.row == 0 {
                let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "add_cell",
                    for: indexPath
                )
                cell.contentView.addSubview(cellAddButton)
                NSLayoutConstraint.activate([
                    cellAddButton.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor),
                    cellAddButton.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor),
                    cellAddButton.widthAnchor.constraint(equalToConstant: 40.0),
                    cellAddButton.heightAnchor.constraint(equalToConstant: 40.0),
                ])
                return cell
            } else if indexPath.row == 1 {
                let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "delete_cell",
                    for: indexPath
                )
                cell.contentView.addSubview(cellDeleteButton)
                NSLayoutConstraint.activate([
                    cellDeleteButton.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor),
                    cellDeleteButton.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor),
                    cellDeleteButton.widthAnchor.constraint(equalToConstant: 40.0),
                    cellDeleteButton.heightAnchor.constraint(equalToConstant: 40.0),
                ])
                return cell
            } else {
                if let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "\(TeamUserCell.self)",
                    for: indexPath
                ) as? TeamUserCell {
                    if let user = viewModel.teamInfoModel?.users[indexPath.row-2] {
                        // 从缓存中获取用户信息
                        if let userId = user.nimUser?.user?.accountId, let nimUser = NEFriendUserCache.shared.getFriendInfo(userId) {
                            user.nimUser = nimUser
                        }
                        cell.user = user
                    }
                    return cell
                }
            }
        } else if !canAdd && canDelete {
            if indexPath.row == 0 {
                let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "delete_cell",
                    for: indexPath
                )
                cell.contentView.addSubview(cellDeleteButton)
                NSLayoutConstraint.activate([
                    cellDeleteButton.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor),
                    cellDeleteButton.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor),
                    cellDeleteButton.widthAnchor.constraint(equalToConstant: 40.0),
                    cellDeleteButton.heightAnchor.constraint(equalToConstant: 40.0),
                ])
                return cell
            } else {
                if let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "\(TeamUserCell.self)",
                    for: indexPath
                ) as? TeamUserCell {
                    if let user = viewModel.teamInfoModel?.users[indexPath.row-1] {
                        // 从缓存中获取用户信息
                        if let userId = user.nimUser?.user?.accountId, let nimUser = NEFriendUserCache.shared.getFriendInfo(userId) {
                            user.nimUser = nimUser
                        }
                        cell.user = user
                    }
                    return cell
                }
            }
        }  else if canAdd && !canDelete {
            if indexPath.row == 0 {
                let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "add_cell",
                    for: indexPath
                )
                cell.contentView.addSubview(cellAddButton)
                NSLayoutConstraint.activate([
                    cellAddButton.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor),
                    cellAddButton.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor),
                    cellAddButton.widthAnchor.constraint(equalToConstant: 40.0),
                    cellAddButton.heightAnchor.constraint(equalToConstant: 40.0),
                ])
                return cell
            } else {
                if let cell = collectionView.dequeueReusableCell(
                    withReuseIdentifier: "\(TeamUserCell.self)",
                    for: indexPath
                ) as? TeamUserCell {
                    if let user = viewModel.teamInfoModel?.users[indexPath.row-1] {
                        // 从缓存中获取用户信息
                        if let userId = user.nimUser?.user?.accountId, let nimUser = NEFriendUserCache.shared.getFriendInfo(userId) {
                            user.nimUser = nimUser
                        }
                        cell.user = user
                    }
                    return cell
                }
            }
        } else {
            if let cell = collectionView.dequeueReusableCell(
                withReuseIdentifier: "\(TeamUserCell.self)",
                for: indexPath
            ) as? TeamUserCell {
                if let user = viewModel.teamInfoModel?.users[indexPath.row] {
                    // 从缓存中获取用户信息
                    if let userId = user.nimUser?.user?.accountId, let nimUser = NEFriendUserCache.shared.getFriendInfo(userId) {
                        user.nimUser = nimUser
                    }
                    cell.user = user
                }
                return cell
            }
        }
        
        return UICollectionViewCell()
    }
    
    override open func collectionView(_ collectionView: UICollectionView,
                                      layout collectionViewLayout: UICollectionViewLayout,
                                      sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if indexPath.row == 0 {
            return CGSize(width: 40, height: 40)
        }
        return CGSize(width: 40 + (NEConstant.screenWidth - 54 - 280)/7, height: 40)
    }
    
    override open func collectionView(_ collectionView: UICollectionView,
                                      didSelectItemAt indexPath: IndexPath) {
        if canAdd && canDelete {
            if indexPath.row == 0 {
                addUser()
            } else if indexPath.row == 1 {
                toMemberList()
            } else {
                //                if let member = viewModel.teamInfoModel?.users[indexPath.row-2],
                //                   let nimUser = member.nimUser {
                //                    if IMKitClient.instance.isMe(nimUser.user?.accountId) {
                //                        Router.shared.use(
                //                            MeSettingRouter,
                //                            parameters: ["nav": navigationController as Any],
                //                            closure: nil
                //                        )
                //                    } else {
                //                        if let uid = nimUser.user?.accountId {
                //                            Router.shared.use(
                //                                ContactUserInfoPageRouter,
                //                                parameters: ["nav": navigationController as Any, "uid": uid],
                //                                closure: nil
                //                            )
                //                        }
                //                    }
                //                }
            }
            
        } else if !canAdd && canDelete {
            if indexPath.row == 0 {
                toMemberList()
            } else {
                //                if let member = viewModel.teamInfoModel?.users[indexPath.row-1],
                //                   let nimUser = member.nimUser {
                //                    if IMKitClient.instance.isMe(nimUser.user?.accountId) {
                //                        Router.shared.use(
                //                            MeSettingRouter,
                //                            parameters: ["nav": navigationController as Any],
                //                            closure: nil
                //                        )
                //                    } else {
                //                        if let uid = nimUser.user?.accountId {
                //                            Router.shared.use(
                //                                ContactUserInfoPageRouter,
                //                                parameters: ["nav": navigationController as Any, "uid": uid],
                //                                closure: nil
                //                            )
                //                        }
                //                    }
                //                }
            }
        } else if canAdd && !canDelete {
            if indexPath.row == 0 {
                addUser()
            }
        } else {
            //            if let member = viewModel.teamInfoModel?.users[indexPath.row],
            //               let nimUser = member.nimUser {
            //                if IMKitClient.instance.isMe(nimUser.user?.accountId) {
            //                    Router.shared.use(
            //                        MeSettingRouter,
            //                        parameters: ["nav": navigationController as Any],
            //                        closure: nil
            //                    )
            //                } else {
            //                    if let uid = nimUser.user?.accountId {
            //                        Router.shared.use(
            //                            ContactUserInfoPageRouter,
            //                            parameters: ["nav": navigationController as Any, "uid": uid],
            //                            closure: nil
            //                        )
            //                    }
            //                }
            //            }
        }
        
    }
    
    override open func toMemberList() {
        let memberController = TeamMembersController(teamId: viewModel.teamInfoModel?.team?.teamId)
        navigationController?.pushViewController(memberController, animated: true)
    }
    
    override open func toMemberRemoveList() {
        let memberRemoveController = TeamMemberRemoveController(teamId: viewModel.teamInfoModel?.team?.teamId)
        navigationController?.pushViewController(memberRemoveController, animated: true)
    }
    
    open override func addUser() {
        Router.shared.register(TeamMemberAddViewRouter) { param in
            print("param:\(param)")
            let nav = param["nav"] as? UINavigationController
            guard let teamId = param["teamId"] as? String else {
                return
            }
            
            let memberAddController = TeamMemberAddController(teamId: teamId)
            nav?.pushViewController(memberAddController, animated: true)
        }
        
        var param = [String: Any]()
        param["nav"] = navigationController as Any
        param["teamId"] = viewModel.teamInfoModel?.team?.teamId
        
        Router.shared.use(TeamMemberAddViewRouter, parameters: param, closure: nil)
        
        //        let memberAddController = TeamMemberAddController(teamId: viewModel.teamInfoModel?.team?.teamId)
        //        navigationController?.pushViewController(memberAddController, animated: true)
    }
}
